import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';

class ForgotPasswordLogic extends GetxController {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController codeController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController confirmPasswordController = TextEditingController();

  final RxString phoneErrorText = "".obs;
  final RxString codeErrorText = "".obs;
  final RxString passwordErrorText = "".obs;
  final RxString confirmPasswordErrorText = "".obs;

  final RxInt countdown = 60.obs;
  final RxBool isRunning = false.obs;
  final RxBool showPassword = false.obs;
  final RxBool showConfirmPassword = false.obs;

  Timer? _timer;
  final Random _random = Random();
  final RxString generatedCode = "".obs;

  final RxBool showCaptcha = false.obs;
  final RxBool captchaVerified = false.obs;
  final RxBool isCaptchaLoading = false.obs;

  // 添加滑块验证码验证方法
  void verifyCaptcha() {
    isCaptchaLoading.value = true;
    // 模拟API验证延迟
    Future.delayed(Duration(seconds: 1), () {
      isCaptchaLoading.value = false;
      captchaVerified.value = true;
      showCaptcha.value = false;
      // 验证通过后自动发送验证码
      sendVerificationCode();
    });
  }

  // 修改获取验证码方法
  void sendVerificationCode() {
    if (phoneController.text.length != 11) {
      Get.snackbar(
          '错误',
          '请输入正确的手机号',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red,
          colorText: Colors.white
      );
      return;
    }

    if (!captchaVerified.value) {
      showCaptcha.value = true;
      return;
    }

    generateNewCode();
    startCountdown();
    Get.snackbar(
        '验证码已发送',
        '请注意查收短信',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white
    );
  }

  // 刷新验证码
  void refreshCaptcha() {
    isCaptchaLoading.value = true;
    Future.delayed(Duration(seconds: 1), () {
      isCaptchaLoading.value = false;
    });
  }
  @override
  void onInit() {
    super.onInit();
    generateNewCode();
  }

  void generateNewCode() {
    generatedCode.value = (1000 + _random.nextInt(9000)).toString();
    debugPrint("生成的验证码: ${generatedCode.value}");
  }

  void startCountdown() {
    if (isRunning.value) return;

    isRunning.value = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdown.value == 0) {
        _resetCountdown();
      } else {
        countdown.value--;
      }
    });
  }

  void _resetCountdown() {
    _timer?.cancel();
    isRunning.value = false;
    countdown.value = 60;
  }

  bool validateForm() {
    bool isValid = true;

    if (!_validatePhone(phoneController.text)) {
      isValid = false;
    }

    if (!_validateCode(codeController.text)) {
      isValid = false;
    }

    if (!_validatePassword(passwordController.text)) {
      isValid = false;
    }

    if (!_validateConfirmPassword(
        passwordController.text,
        confirmPasswordController.text
    )) {
      isValid = false;
    }

    return isValid;
  }

  bool _validatePhone(String phone) {
    if (phone.isEmpty) {
      phoneErrorText.value = "请输入手机号码";
      return false;
    }
    if (phone.length != 11 || !RegExp(r'^[0-9]{11}$').hasMatch(phone)) {
      phoneErrorText.value = "请输入正确的手机号码";
      return false;
    }
    phoneErrorText.value = "";
    return true;
  }

  bool _validateCode(String code) {
    if (code.isEmpty) {
      codeErrorText.value = "请输入验证码";
      return false;
    }
    if (code != generatedCode.value) {
      codeErrorText.value = "验证码不正确";
      return false;
    }
    codeErrorText.value = "";
    return true;
  }

  bool _validatePassword(String password) {
    if (password.isEmpty) {
      passwordErrorText.value = "请输入新密码";
      return false;
    }
    if (password.length < 6) {
      passwordErrorText.value = "密码长度不能少于6位";
      return false;
    }
    passwordErrorText.value = "";
    return true;
  }

  bool _validateConfirmPassword(String password, String confirmPassword) {
    if (confirmPassword.isEmpty) {
      confirmPasswordErrorText.value = "请再次输入密码";
      return false;
    }
    if (password != confirmPassword) {
      confirmPasswordErrorText.value = "两次输入的密码不一致";
      return false;
    }
    confirmPasswordErrorText.value = "";
    return true;
  }

  Future<void> submit() async {
    if (validateForm()) {
      // 这里应该是你的API调用，模拟成功
      Get.back();
      Get.snackbar(
          '成功',
          '密码已重置，请使用新密码登录',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green,
          colorText: Colors.white
      );
    }
  }

  @override
  void onClose() {
    _timer?.cancel();
    phoneController.dispose();
    codeController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    super.onClose();
  }
}